/* eslint-disable no-debugger */
import i18n from "i18next";
import { HashRouter } from "react-router-dom";
import { ConfigProvider, Spin, theme } from "antd";
// import AuthRouter from "@/routers/components/AuthRouter";
import rootRouter from "@/routers";
import { RootState, useDispatch, useSelector } from "@/store";
import zhCN from "antd/lib/locale/zh_CN";
import enUS from "antd/lib/locale/en_US";
import { Suspense, useEffect, useState } from "react";
import { getBrowserLang } from "@/utils/localeUtils";
import { getUserInfo, setLanguage, updateSystemName } from "@/store/modules/global";
import useTheme from "@/hooks/useTheme";
import useToken from "@/hooks/useToken";
import { WebSocketProvider } from "./components/WebSocketProvide";
import RouterWaiter from "./components/RouterWaiter";
import onRouteBefore from "./routers/components/AuthRouter";
import { RouterContextProvider } from "./components/RouterContext";
const App = () => {
	const dispatch = useDispatch();
	const { token } = useToken();
	const { language, assemblySize, themeConfig } = useSelector((state: RootState) => state.global);
	const [i18nLocale, setI18nLocale] = useState(zhCN);
	// 全局使用主题
	useTheme();
	// 设置 antd 语言国际化
	const setAntdLanguage = () => {
		// 如果 redux 中有默认语言就设置成 redux 的默认语言，没有默认语言就设置成浏览器默认语言
		if (language && language == "zh") return setI18nLocale(zhCN);
		if (language && language == "en") return setI18nLocale(enUS);
		if (getBrowserLang() == "zh") return setI18nLocale(zhCN);
		if (getBrowserLang() == "en") return setI18nLocale(enUS);
	};

	useEffect(() => {
		// 全局使用国际化
		i18n.changeLanguage(language || getBrowserLang());
		dispatch(setLanguage(language || getBrowserLang()));
		setAntdLanguage();
	}, [language]);

	const checkLogin = () => {
		if (token) {
			return true;
		} else {
			return false;
		}
	};

	useEffect(() => {
		const timer = setTimeout(() => {
			const isLoggedIn = checkLogin();
			if (isLoggedIn) {
				// @ts-ignore
				dispatch(getUserInfo());
			}
		}); // 延迟1秒执行
		return () => clearTimeout(timer);
	}, []);
	return (
		<HashRouter>
			<ConfigProvider
				prefixCls="hov"
				locale={i18nLocale}
				componentSize={assemblySize}
				theme={{
					algorithm: [themeConfig.isDark ? theme.darkAlgorithm : theme.defaultAlgorithm]
				}}
			>
				<WebSocketProvider>
					{/* <AuthRouter>
						<Router />
					</AuthRouter> */}
					<RouterContextProvider>
						<RouterWaiter
							loading={
								<Suspense
									fallback={
										<Spin
											size="large"
											style={{
												display: "flex",
												alignItems: "center",
												justifyContent: "center",
												height: "calc(100vh - 100px)"
											}}
										/>
									}
								/>
							}
							routes={rootRouter}
							onRouteBefore={onRouteBefore}
						/>
					</RouterContextProvider>
				</WebSocketProvider>
			</ConfigProvider>
		</HashRouter>
	);
};

export default App;
